package network2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//接收
public class Talkreceive implements Runnable {
    private DatagramSocket server;
    private String from;

    public Talkreceive(int port, String from) {
        this.from = from;
        try {
            server = new DatagramSocket(port);
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void run() {
        while (true) {
            byte[] bytes = new byte[1024 * 35];
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);

            try {
                server.receive(packet);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            byte[] data = packet.getData();
            int length = packet.getLength();
            String s = new String(data, 0, length);
            System.out.println("消息" + s);
            if ("bye".equals(s)) {
                break;
            }
        }
        server.close();
    }
}
